package com.ice.body.dict.controller;

import com.ice.base.constant.UserConstants;
import com.ice.base.controller.BaseController;
import com.ice.base.model.SysLoginModel;
import com.ice.base.model.TreeSelect;
import com.ice.base.result.AjaxResult;
import com.ice.base.result.ResponseResult;
import com.ice.base.util.BaseUtil;
import com.ice.body.dict.model.SysDept;
import com.ice.body.dict.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * Created with GuoYanBin.
 * Description:
 * Date: 2022-04-21
 * Time: 10:28
 */
@RestController
@RequestMapping("/api/dept")
@ApiIgnore(value = "部门管理")
public class SysDeptController extends BaseController{
    //---------------------------企业部门-----------------------start
    @Resource
    private DeptService deptService;


    @ApiOperation(value = "查询部门下一级所有单位")
    @GetMapping("/selectChildren")
    public AjaxResult selectChildren(Long deptId) {
        AjaxResult r = ResponseResult.success();
        SysLoginModel currLoginModel = BaseUtil.getCurrLoginModel();
        if(null == deptId){
            deptId = currLoginModel.getDeptId();
        }
        List<SysDept> depts = deptService.selectChildren(deptId);
        return AjaxResult.success(depts);
    }


    @ApiOperation(value = "获取部门下拉树列表")
    @GetMapping("/treeSelect")
    public AjaxResult treeSelect(SysDept dept) {
        AjaxResult r = ResponseResult.success();

        SysLoginModel currLoginModel = BaseUtil.getCurrLoginModel();
        Long deptId = currLoginModel.getDeptId();
        List<SysDept> depts ;
        if(currLoginModel.getUserName().equals("admin")){
            depts = deptService.selectDeptList(dept);
        }else{
            depts = deptService.selectChildrenDeptById(deptId);
        }
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(depts);
        r.setData(treeSelects);

        return AjaxResult.success(treeSelects);
    }



    @ApiOperation(value = "部门-新增")
    @PostMapping("/add")
    public AjaxResult insert_DictDept(SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ResponseResult.errors(0,"新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(BaseUtil.getCurrLoginModel().getRealName());
        return toAjax(deptService.insertDept(dept));
    }

    @ApiOperation(value = "获取部门列表")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    @ApiOperation(value = "查询部门列表（排除节点）")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    @ApiOperation(value = "根据部门编号获取详细信息")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }








    @ApiOperation(value = "加载对应角色部门列表树")
    @GetMapping(value = "/roleDeptTreeSelect/{roleId}")
    public AjaxResult roleDeptTreeSelect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = ResponseResult.success();
  /*      ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));*/
        return ajax;
    }



    @ApiOperation(value = "修改部门")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ResponseResult.errors(0,"修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(BaseUtil.getCurrLoginModel().getUserName());
        return toAjax(deptService.updateDept(dept));
    }

    @ApiOperation(value = "删除部门")
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
    //---------------------------企业部门-----------------------end
}
